<?php

namespace App\Service\Coin;

use App\Helpers\ConfigUtil;
use App\Model\PayOrder;
use App\Model\UserActLog;
use App\Service\BaseService;

/**
 * 商品设置
 */
class SubjectsSerice extends BaseService
{
    public function handle()
    {
        $userId = $this->getUserId();
        $newPay = $this->curVersion >= env('NEW_PAYWAY_VERSION', '1.0.0');
        $platform = $this->request->input('platform', 2);
        $appId = $this->request->input('appid', 1);
        $from = $this->request->input('from', 0);
        $channel = $platform == 1 ? 'apple' : 'wechat';
        //是否首次支付
        $checkPay = PayOrder::checkSuccess($userId);
        $firstPay = $checkPay ? false : true;
        $ret['list'] = ConfigUtil::getRecharge(0, $channel, false, $firstPay);
        $ret['tip'] = ''; //'注册当天充值可额外获得4金币，首充可额外赠送20金币';
        $newChannels = [
            ['name' => '微信支付', 'channel' => 'wechat', 'selected' => 1],
//            ['name' => '支付宝支付', 'channel' => 'alipay', 'selected' => 0],
        ];
        $ret['pay_channel'] = $newChannels;
        //协议文档
        $ret['protocol'] = 'http://www.hudongailian.com/recharge_protocol.html';
        $this->packList($ret['list'], $firstPay);
        //行为日志
        $userId && UserActLog::addRecord($userId, UserActLog::ACT_RECHARGE_OPEN, json_encode(['from' => $from]));
        return $ret;
    }

    /**
     * 获取充值项
     */
    function packList(&$list = [], $firstPay = true)
    {
        if ($firstPay) $validIds = explode(',', env('PAY_FIRST_SUBJECTS_ID', '4,5,6,9,10,12'));
        else $validIds = explode(',', env('PAY_AFTER_SUBJECTS_ID', '4,5,6,10,12,13'));
        return $this->selectSubjects($list, $validIds);
    }

    function selectSubjects(&$list = [], $validIds = [])
    {
        if (!$validIds) return;
        foreach ($list as $k => $subject) {
            if (!in_array($subject['subject_id'], $validIds)) unset($list[$k]);
        }
        $list = array_values($list);
    }
}
